package com.caifu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.caifu.bean.Result;
import com.caifu.excel.ExcelDatas;
import com.caifu.pojo.ExcelData;
import com.caifu.pojo.SysUser;
import com.caifu.service.*;
import com.caifu.util.Util;
import com.caifu.vo.DataUserAgeVo;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 数据看板
 *
 * @author tww
 * ClassName: DataController.java、
 * createTime: 2020年11月26日 10:24:39
 **/
@Controller
@RequestMapping("data")
public class DataController extends AbstractController {
    private static final Logger logger = LoggerFactory.getLogger(DataController.class);

    @Resource
    private BmmUserinfoService bmmUserinfoService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private BmCouponsRecordService bmCouponsRecordService;

    @Resource
    private SysOrganizationService sysOrganizationService;

    @Resource
    private BmActivityManagerService bmActivityManagerService;

    /**
     * 跳数据看板页
     */
    @GetMapping("toDataPage")
    public String toHaircutInfoPage() {
        return "data/data";
    }

    /**
     * 根据flag获取理发、缝纫信息总数  1.理发 2.缝纫
     */
    @GetMapping("getLiFaOrFengRenByFlag")
    @ResponseBody
    public Map<String, Object> getLiFaOrFengRenByFlag(String flag) {
        SysUser user = getUser();
        Map<String, Object> map = new HashMap<>(10);
        try {
            map = bmmUserinfoService.getLiFaOrFengRenByFlag(flag, user);
            map.put("code", "200");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            map.put("code", "500");
            map.put("msg", msg);
            e.printStackTrace();
            return map;
        }
    }

    /**
     * 获取优惠券年龄段分布
     */
    @GetMapping("getUserinfoAge")
    @ResponseBody
    public Result<Object> getUserinfoAge(DataUserAgeVo dataUserAgeVo) {
        SysUser user = getUser();
        try {
            List<Map<String, Object>> lists = bmmUserinfoService.getUserinfoAge(dataUserAgeVo, user);
            return success(200, "", lists);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            e.printStackTrace();
            return error(500, msg);
        }
    }

    /**
     * 近六月核销率
     */
    @GetMapping("getPinRate")
    @ResponseBody
    public Map<String, Object> getPinRate() {
        SysUser user = getUser();
        Map<String, Object> map = new HashMap<>();
        try {
            return bmmUserinfoService.getPinRate(user);
        } catch (Exception e) {
            map.put("code", "-1");
            e.printStackTrace();
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            e.printStackTrace();
            return map;
        }
    }

    /**
     * 获取本月、本年理发店或缝纫店核销 type 1.理发店 2.缝纫店 flag 1.本月 2.本年
     */
    @GetMapping("getPinByType")
    @ResponseBody
    public Result<Object> getPinByType(String type, String flag, String all) {
        SysUser user = getUser();
        try {
            Map<String, Object> map = bmmUserinfoService.getPinByType(type, flag, user, all);
            return success(200, "success", map);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            e.printStackTrace();
            return error(500, msg);
        }
    }


    /**
     * 获取理发、缝纫近12月核销
     */
    @GetMapping("getLast12Months")
    @ResponseBody
    public Result<Object> getLast12Months() {
        SysUser user = getUser();
        try {
            Map<String, Object> map = bmmUserinfoService.getLast12Months(user);
            return success(200, "success", map);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            e.printStackTrace();
            return error(500, msg);
        }
    }


    /**
     * 导出员工信息 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("exportExcel")
    public void exportExcel(String type, String flag, HttpServletResponse response) throws IOException {
        SysUser user = getUser();
        ExcelWriter excelWriter = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = String.valueOf(System.currentTimeMillis());
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里 指定文件
            excelWriter = EasyExcel.write(response.getOutputStream(), ExcelData.class).build();
            // 去调用写入,这里我调用了五次，实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面
            List<Map<String, Object>> excelData = bmCouponsRecordService.getExcelData(type, flag, user);
            if (excelData.size() > 0) {
                for (int i = 0; i < excelData.size(); i++) {
                    // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                    WriteSheet writeSheet = EasyExcel.writerSheet(i, excelData.get(i).get("name").toString()).build();
                    // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                    List<ExcelData> excelDataList = (List<ExcelData>) excelData.get(i).get("data");
                    excelWriter.write(excelDataList, writeSheet);
                }
            }
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>(10);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
